<template :key ="componentKey" default-active="1">
  <div class="main">
    <el-affix :offset="0">
      <ComAffix /> <!-- 使用组件 -->
    </el-affix>
    <div class="bode">
      <div class="page">
        <div class="side">
          <div class="message-title">
            <el-icon class="mr-2"><Message /></el-icon>
            <span class="center">消息中心</span>
          </div>

          <el-menu :key ="componentKey" default-active="1">
            <!-- 动态生成用户列表 -->
            <el-menu-item
              v-for="user in friend"
              :key="user.id"
              :index="user.id.toString()"
              @click="handleSelectChat(user)"
            >
              <template #title>
                <!-- 正确嵌套：徽章包裹头像 -->
                <div class="badge-container">
                    <el-avatar size="medium" :src="user.avatar || 'https://picsum.photos/100/100?random=' + user.id" />
                </div>
                <div class="com">
                  <span>{{ user.name }}&nbsp;</span><br>
                  <span  class="truncate-text">{{ [user.lastMessageContent] }}</span>
                </div>
              </template>
            </el-menu-item>
          </el-menu>
        </div>
        <div class="chat">
          <div class="chat-head">
            <span v-if="currentChat">{{ currentChat.name }}<el-icon><ChatDotRound /></el-icon></span>
          </div>
          <div class="chat-input">
            <div v-if="currentChat && currentChat.messages.length > 0" class="message-list" ref="messageListRef">
              <div
                v-for="(msg, index) in currentChat.messages"
                :key="index"
                :class="msg.isSelf ? 'self-message-container' : 'other-message-container'"
              >
                <!-- 对方消息：头像在左，气泡在右 -->
                <div v-if="!msg.isSelf" class="other-message-wrapper">
                  <el-avatar
                    :size="36"
                    :src="currentChat.avatar || 'https://picsum.photos/100/100?random=' + currentChat.id"
                    class="message-avatar"
                  />
                  <div class="message-content">
                    <div class="message-time">{{ msg.timestamp }}</div>
                    <div class="other-message">
                      <!-- 文本消息：直接显示内容 -->
                      <template v-if="msg.type === 'text'">
                        {{ msg.content }}
                      </template>

                      <!-- 图片消息：通过 URL 加载图片 -->
                      <template v-if="msg.type === 'image'">
                        <div class="image - message">
                          <img :src="msg.content" class="chat - image" alt="聊天图片" @error="handleImageError($event)" style="max-width: 200px ;max-height: 200px;" @click="zoomImage(msg.content)">
                        </div>
                      </template>
                    </div>
                  </div>
                </div>

                <!-- 自己消息：头像在右，气泡在左 -->
                <div v-else class="self-message-wrapper">
                  <div class="message-content self-content">
                    <div class="message-time self-time">{{ msg.timestamp }}</div>
                    <div class="self-message">
                        <template v-if="msg.type === 'text'">
                          {{ msg.content }}
                        </template>

                        <!-- 图片消息：通过 URL 加载图片 -->
                        <template v-if="msg.type === 'image'">
                          <!-- 核心：用 img 标签的 src 指向 URL -->
                            <div class="image - message">
                              <img :src="msg.content" class="chat - image" alt="聊天图片" @error="handleImageError($event)" style="max-width: 200px; max-height: 200px;" @click="zoomImage(msg.content)">
                            </div>
                        </template>
                    </div>
                  </div>
                  <el-avatar
                    :size="36"
                    :src= useStore.user.avatar
                    class="message-avatar"
                  />
                </div>
              </div>
            </div>

            <!-- 选中会话但无消息时显示提示 -->
            <el-empty
              description="开始聊天吧！\（ovo）/"
              v-else-if="currentChat && currentChat.messages.length === 0"
            />

            <!-- 未选中会话时显示空状态 -->
            <el-empty
              description="请选择一个会话开始聊天"
              v-else
            />
          </div>
          <div class="text-input">
            <!-- 编辑器组件，绑定 sendMessage 事件 -->
            <QQEditor ref="editorRef" @send="sendMessage" />
          </div>
        </div>
      </div>
    </div>
    <!-- 图片放大查看遮罩层 -->
    <div
      v-if="isImageZoomed"
      class="image-zoom-mask"
      @click="handleMaskClick"
    >
      <!-- 关闭按钮 -->
      <button class="close-btn" @click="closeZoomedImage">×</button>

      <!-- 放大的图片 -->
      <div class="zoomed-image-container">
        <img
          :src="zoomedImageUrl"
          class="zoomed-image"
          alt="放大查看"
          @load="adjustZoomedImagePosition"
        >
      </div>
    </div>
  </div>
</template>

<script setup>
import { nextTick, ref, onMounted, watch, onActivated } from 'vue';
import ComAffix from "@/components/ComAffix.vue";
import QQEditor from "@/components/inputPage.vue";
import { createConversationAPI } from '@/api/conversation.js';
import { ChatDotRound, Message } from '@element-plus/icons-vue';
import { useUserStore } from '@/stores/index.js';
import { ElMessage } from "element-plus";
import { getAllConversations, getMessagesByConversationId, sendMessageAPI } from "@/api/message.js";
import { useRoute, useRouter } from 'vue-router';

const router = useRouter();
const route = useRoute();
const useStore = useUserStore();
const editorRef = ref(null);
const currentChat = ref(null);
const friend = ref([]);
const loading = ref(false);
const messageLoading = ref(false);
const messageListRef = ref(null);
const componentKey = ref(0);
// 图片放大相关状态
const isImageZoomed = ref(false); // 是否显示放大的图片
const zoomedImageUrl = ref(''); // 放大的图片URL

// 点击图片放大
const zoomImage = (url) => {
  zoomedImageUrl.value = url;
  isImageZoomed.value = true;
  // 隐藏页面滚动条，避免背景滚动
  document.body.style.overflow = 'hidden';
};

// 关闭放大的图片
const closeZoomedImage = () => {
  isImageZoomed.value = false;
  zoomedImageUrl.value = '';
  // 恢复页面滚动
  document.body.style.overflow = '';
};

// 点击遮罩层空白处关闭
const handleMaskClick = (e) => {
  if (e.target === e.currentTarget) {
    closeZoomedImage();
  }
};
/**
 * 初始化会话列表（可重复调用）
 */
const initConversations = async () => {
  try {
    currentChat.value = null;
    if (!useStore.user.id) {
      ElMessage.warning('请先登录');
      return;
    }

    loading.value = true;
    const { data: response } = await getAllConversations(useStore.user.id);

    if (response.code === 1 && Array.isArray(response.data)) {
      friend.value = response.data.map(conversation => ({
        id: conversation.id,
        name: conversation.targetUserName || '未知用户',
        avatar: conversation.targetAvatar,
        targetUserId: conversation.targetUserId,
        unreadCount: conversation.unreadCount || 0,
        lastMessageContent: conversation.lastMessageContent || "暂无消息",
        messages: []
      }));

      const receiverId = route.query.receiverId;
      if (receiverId) {
        await handleAutoSwitchConversation(receiverId);
      }
    } else {
      ElMessage.warning(response.msg || '获取会话列表失败');
    }
  } catch (error) {
    console.error('初始化会话失败:', error);
    ElMessage.error('刷新会话列表失败');
    friend.value = [];
  } finally {
    loading.value = false;
  }
};

/**
 * 统一处理消息发送（支持文本和图片）
 * @param {Object} msgData - 消息对象 { type, content }
 */
const handleSendMessage = async (msgData) => {
  if (!currentChat.value || !useStore.user.id) return;

  const { type, content } = msgData;
  // 内容校验（文本不能为空，图片URL不能为空）
  if ((type === 'text' && !content.trim()) || (type === 'image' && !content)) {
    return;
  }

  try {
    messageLoading.value = true;

    // 1. 前端临时添加消息（优化体验）
    const newMessage = {
      type: type, // 新增：消息类型（text/image）
      content: content,
      isSelf: true,
      timestamp: new Date().toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
      }),
      senderId: useStore.user.id
    };
    currentChat.value.messages.push(newMessage);
    scrollToBottom();

    // 2. 调用后端接口发送消息（携带类型）
    const messageParams = {
      conversationId: currentChat.value?.id,
      senderId: useStore.user?.id,
      receiverId: currentChat.value?.targetUserId,
      content: content,
      type: type || 'text'
    };

// 图片消息补充额外参数
    if (type === 'image') {
      // 假设从图片URL中提取文件名（可选）
      const fileName = content.split('/').pop();
      Object.assign(messageParams, {
        fileName: fileName, // 传递文件名
        size: content.length // 简单示例，实际可通过File对象获取真实大小
      });
    }

// 调用API
    await sendMessageAPI(messageParams);

    // 3. 刷新消息列表，确保同步最新数据
    await loadConversationMessages(currentChat.value.id);

    // 4. 清空编辑器（仅文本消息需要）
    if (type === 'text' && editorRef.value) {
      editorRef.value.clearContent();
    }

  } catch (error) {
    console.error("发送消息失败:", error);
    ElMessage.error('消息发送失败');
    // 失败时移除临时添加的消息
    currentChat.value.messages.pop();
  } finally {
    messageLoading.value = false;
  }
};

/**
 * 接收子组件的消息（文本/图片）
 */
const sendMessage = (msgData) => {
  handleSendMessage(msgData);
};

/**
 * 选择会话并加载消息
 */
const handleSelectChat = async (conversation) => {
  try {
    const formattedMessages = await loadConversationMessages(conversation.id);

    currentChat.value = {
      id: conversation.id,
      name: conversation.name,
      avatar: conversation.avatar,
      targetUserId: conversation.targetUserId,
      messages: formattedMessages || []
    };

    scrollToBottom();
  } catch (error) {
    console.error('选择会话失败:', error);
    ElMessage.error('切换会话失败');
  }
};

/**
 * 滚动到底部
 */
const scrollToBottom = () => {
  nextTick(() => {
    if (messageListRef.value) {
      messageListRef.value.scrollTop = messageListRef.value.scrollHeight;
    }
  });
};

/**
 * 加载会话消息（扩展支持类型）
 */
const loadConversationMessages = async (conversationId) => {
  try {
    const response = await getMessagesByConversationId(conversationId);
    if (response.data.code === 1 && Array.isArray(response.data.data)) {
      const currentUserId = useStore.user.id;
      const formattedMessages = response.data.data.map(msg => {
        // 临时方案：通过内容是否为URL判断类型（仅作兼容，优先让后端加type字段）
        const isImage = msg.content.startsWith('http://') || msg.content.startsWith('https://');
        return {
          ...msg,
          isSelf: msg.senderId === currentUserId,
          timestamp: msg.createTime || new Date().toLocaleTimeString(),
          type: msg.type || (isImage ? 'image' : 'text') // 兼容处理
        };
      });

      // 更新会话最后一条消息
      const conversationIndex = friend.value.findIndex(c => c.id === conversationId);
      if (conversationIndex !== -1) {
        const lastMsg = formattedMessages[formattedMessages.length - 1];
        friend.value[conversationIndex].lastMessageContent =
          lastMsg?.type === 'image' ? '[图片]' : (lastMsg?.content || "暂无消息");
      }

      return formattedMessages;
    }

    ElMessage.error('加载最新消息失败');
    return [];
  } catch (error) {
    console.error('加载会话消息失败:', error);
    ElMessage.error('加载最新消息失败');
    return [];
  }
};

/**
 * 处理自动切换会话（创建新会话或切换到已存在会话）
 */
const handleAutoSwitchConversation = async (receiverId) => {
  if (!receiverId) {
    console.log('URL中未包含 receiverId，不自动切换会话');
    return;
  }
  if (!useStore.user.id) {
    ElMessage.warning('请先登录后再操作');
    return;
  }

  const isNewConversation = !friend.value.some(conv => {
    const targetId = conv.targetUserId ?? '';
    const targetReceiverId = receiverId ?? '';
    return targetId.toString() === targetReceiverId.toString();
  });

  if (isNewConversation) {
    try {
      const createResponse = await createConversationAPI(
        useStore.user.id,
        receiverId
      );

      if (createResponse.data.code !== 1) {
        ElMessage.error(`创建会话失败：${createResponse.data.msg || '未知错误'}`);
        return;
      }

      const newConversation = {
        id: createResponse.data.data.id || `new_${Date.now()}_${receiverId}`,
        name: createResponse.data.data.targetUserName || '未知用户',
        avatar: createResponse.data.data.targetAvatar || '',
        targetUserId: receiverId,
        lastMessageContent: '暂无消息',
        messages: []
      };

      friend.value = [...friend.value, newConversation];
      componentKey.value += 1;
      await nextTick();

      await handleSelectChat(newConversation);
      return;
    } catch (error) {
      console.error('自动创建会话失败：', error);
      ElMessage.error('创建会话失败，请稍后重试');
      return;
    }
  }

  const existingConversation = friend.value.find(conv => {
    const targetId = conv.targetUserId ?? '';
    const targetReceiverId = receiverId ?? '';
    return targetId.toString() === targetReceiverId.toString();
  });

  if (existingConversation) {
    console.log(`找到现有会话，自动切换到用户 ${receiverId}`);
    await handleSelectChat(existingConversation);
  } else {
    ElMessage.warning('未找到对应的会话');
  }
};

/**
 * 监听路由变化，自动刷新会话列表
 */
watch(
  () => route.fullPath,
  async (newPath, oldPath) => {
    if (newPath.includes('/chat')) {
      await initConversations();
    }
  },
  { immediate: true }
);

/**
 * 组件挂载时初始化
 */
onMounted(async () => {
  await initConversations();
});

/**
 * 组件激活时初始化（适用于 keep-alive 缓存的场景）
 */
onActivated(async () => {
  await initConversations();
});

</script>

<style scoped lang="scss">
.main {
  display: grid;
  background-color: #f6f3f3;
}

.bode {
  display: grid;
  justify-content: center;
}

.page {
  display: flex;
  justify-content: center;
  width: 100%; /* 占满父容器 */
  background: linear-gradient(135deg, #c3dbe8, #ffffff);
  box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);

  .side {
    flex: 0 0 20%; /* 占 20% 宽度 */
  }

  .chat {
    flex: 1; /* 占剩余 80% 宽度 */
    display: grid;
    width: 800px;
    margin-left: 15px;
  }

  .chat-head {
    width: 100%;
    padding: 10px;

    .right {
      margin-left: auto;
    }
  }

  .chat-input {
    height: 350px; /* 设置固定高度，根据需要调整 */
    overflow-y: auto; /* 超出高度时显示垂直滚动条 */
    padding: 10px;
  }

  .text-input {
    box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
  }
}

.el-menu {
  height: 100%;
  background: rgba(255, 255, 255, 0.83);
 margin-left: 20px;
}

.el-menu-item {
  border-top: 1px solid #b3b2b2;
  gap: 10px;

  .com {
    display: flex;
  }
}

.center {
  font-size: 20px;
}

.text {
  font-size: 14px;
}

.box-card {
  width: 480px;
}

.badge-container {
  position: relative;
}

span {
  justify-content: center;
  display: flex;
}

.message-list {
  display: flex;
  background: #ffffff;
  flex-direction: column;
  margin-right: 0.8rem;
  gap: 16px;
  height: 350px;
  overflow-y: auto;

  // 消息容器（包含头像和气泡）
  .other-message-container {
    display: flex;
    padding: 0 12px;
  }

  // 对方消息布局
  .other-message-wrapper {
    display: flex;
    align-items: flex-start;
    gap: 8px;
  }

  // 自己消息布局
  .self-message-wrapper {
    display: flex;
    align-items: flex-start; // 顶部对齐
    gap: 8px;
    width: 100%; // 撑满容器，确保能靠右对齐
    justify-content: flex-end; // 整体内容靠右
    // 不需要 flex-direction: row-reverse，改用以下方式
  }

  // 自己的头像样式（强制靠右侧）
  .self-message-wrapper .message-avatar {
    order: 2; // 调整头像的排列顺序（放在内容后面）
    margin-left: 10px; // 头像左侧留白
    margin-right: 0; // 清除右侧默认间距
  }

  // 自己的消息内容（放在头像左侧）
  .self-message-wrapper .message-content {
    order: 1; // 内容排在前面
  }

  // 消息时间
  .message-time {
    font-size: 12px;
    color: #999;
    margin-bottom: 4px;
    padding: 0 4px;
  }

  // 自己消息的时间靠右
  .self-time {
    text-align: right;
  }

  // 对方消息气泡
  .other-message {
    display: inline-block;
    background-color: #eac7c7;
    padding: 8px 12px;
    border-radius: 18px;
    border-top-left-radius: 4px; // 使气泡左上角更尖，类似QQ效果
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
    text-align: left;
    line-height: 1.4;
  }

  // 自己消息气泡
  .self-message {
    display: inline-block;
    background-color: #99daf6;
    float: right;
    padding: 8px 12px;
    border-radius: 18px;
    border-top-right-radius: 4px; // 使气泡右上角更尖，类似QQ效果
    text-align: left;
    line-height: 1.4;
  }

  // 消息头像
  .message-avatar {
    flex-shrink: 0; // 防止头像被压缩
  }

}

.el-avatar {
  margin-right: 10px; /* 调整头像与消息内容的间距 */
  vertical-align: middle; /* 垂直居中 */
}

.QQEditor {
  width: 100%;
}
.truncate-text {
  display: inline-block;
  max-width: 100px; /* 根据需要调整最大宽度 */
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
//放大图表
/* 图片放大遮罩层 */
.image-zoom-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.9); // 黑色半透明背景
  z-index: 9999; // 确保在最上层
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

/* 关闭按钮 */
.close-btn {
  position: absolute;
  top: 20px;
  right: 20px;
  color: white;
  font-size: 30px;
  background: transparent;
  border: none;
  cursor: pointer;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  &:hover {
    background-color: rgba(255, 255, 255, 0.2);
    border-radius: 50%;
  }
}

/* 放大的图片容器 */
.zoomed-image-container {
  max-width: 90%;
  max-height: 90%;
  position: relative;
}

/* 放大的图片 */
.zoomed-image {
  max-width: 100%;
  max-height: 90vh; // 限制最大高度为视口的90%
  object-fit: contain; // 保持图片比例
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.5);
}
.image-message {
           background-color: transparent; // 去掉背景色
           padding: 0; // 去掉内边距
           border-radius: 0; // 去掉圆角
           box-shadow: none; // 去掉阴影
         }
</style>
